(function($) {
  function swfUploadAddQueue(file) {
    $div = '<div class="progressWrapper" id="'+ file.id +'">' + 
      '<div class="progressContainer blue"><a class="progressCancel" style="visibility:hidden;"></a>' +
      '<div class="progressName">'+ file.name + ' - '+ file.size + ' bytes </div>' +
      '<div class="progressBarStatus">'+ Drupal.settings.photolist.translate.pending +'</div>' +
      '<div class="progressBarComplete" style=""> </div>' +
     '</div></div>';
    $('#swfUploadProgress').show();
    $('#swfUploadProgress').append($div);
  }
  
  function addPhoto(file, json) {
    $li = '<li id="photo-' + json.fid + '">' +
      '<span>' + json.image +
        '<a href="#' + json.fid + '" class="delete-btn">xóa hình</a>' +
      '</span>' +
      '<p class="desc-img" id="photo-desc-' + json.fid + '">'+ Drupal.settings.photolist.translate.edit_desc +'</p>' +
      '</li>';
    $('#photolist-empty').hide();
    if (!$('#photolist-list').size()) {
      $('#photolist').before('<div id="photolist-list">' + Drupal.settings.photolist.translate.list_image + '<\/div>');
    }
    $('#photolist-list').show();
    if (Drupal.settings.photolist.displayOrder)
      $('#photolist').prepend($li);
    else $('#photolist').append($li);
    $('.swfUploadSave:hidden').fadeIn('fast');
    initFancybox();
  }
  
  function _initFancybox() {
    $('a.photolist-thumbnail-link').fancybox( {
      overlayShow : true,
      hideOnContentClick : false,
      titleShow : true
    });
  }
  
  function initFancybox() {
    $('a.photolist-thumbnail-link').once('fancybox', function() {
      _initFancybox();
    });
  }
  
  var swfUploadCount = 0;
  
  Drupal.behaviors.photolist = {
    attach : function() {
      swfUploadSettings = {
        upload_url: Drupal.settings.photolist.uploadUrl,
        flash_url: Drupal.settings.photolist.flashUrl,
        post_params: Drupal.settings.photolist.token,
        
        // Button Settings
        button_image_url : Drupal.settings.photolist.button,
        button_placeholder : $('#swfUploadButton')[0],
        button_width: 74,
        button_height: 27,
        
        // File settings
        file_size_limit : Drupal.settings.photolist.uploadSize,
        file_types : Drupal.settings.photolist.extensions,
        file_types_description : "All Image Files",
        file_upload_limit : Drupal.settings.photolist.queueSize,
        file_queue_limit : 0,
        
        custom_settings: {},
        
        // Debug settings
        debug: false
      };
      
      $("#swfUploadButton").swfupload(swfUploadSettings)
        .bind('swfuploadLoaded', function(event){})
        .bind('fileQueued', function(event, file){
          swfUploadAddQueue(file);
          // start the upload since it's queued
          $(this).swfupload('startUpload');
        })
        .bind('fileQueueError', function(event, file, errorCode, message){})
        .bind('uploadStart', function(event, file){
          $('#' + file.id + ' .progressBarStatus').html(Drupal.settings.photolist.translate.uploading);
        })
        .bind('uploadProgress', function(event, file, bytesLoaded){
          $('#' + file.id + ' .progressBarStatus').html(Drupal.settings.photolist.translate.uploading + Math.round((bytesLoaded/file.size)*100).toString()+ '%');
        })
        .bind('uploadSuccess', function(event, file, serverData){
          $('#' + file.id + ' .progressBarStatus').html(Drupal.settings.photolist.translate.completed);
          serverData = $.parseJSON(serverData);
          // console.log(serverData);
          
          if (typeof serverData.result != 'undefined' && !serverData.result) {
            $('#' + file.id + ' .progressContainer').removeClass('blue').addClass('red');
            $('#' + file.id + ' .progressBarStatus').html(serverData.error);
            //console.error(serverData.error);
          } else {
            swfUploadCount++;
            $('#' + file.id).slideUp('fast', function() {
              $(this).remove();
              if (!$('#swfUploadProgress div').size()) $('#swfUploadProgress').fadeOut('fast');
            });
            $('#swfUploadStatus').html(swfUploadCount.toString() + Drupal.settings.photolist.translate.status);
            
            //console.log(serverData);
            addPhoto(file, serverData);
          }
        })
        .bind('uploadComplete', function(event, file){
          // upload has completed, lets try the next one in the queue
          $(this).swfupload('startUpload');
        })
        .bind('uploadError', function(event, file, errorCode, message){
          $('#' + file.id + ' .progressContainer').removeClass('blue').addClass('red');
          $('#' + file.id + ' .progressBarStatus').html(message);
          //console.log('Error ' + errorCode + ': ' + message);
        });
      
      initFancybox();
      
      // Delete photo
      $('#photolist .delete-btn').live('click', function() {
        if (confirm(Drupal.settings.photolist.translate.confirm_delete)) {
          var fid = this.hash.replace('#', '');
          var remove_url = Drupal.settings.photolist.removeUrl + '/' + fid;
          
          $.ajax({
            url: remove_url,
            success: function(data) {
              //console.log(data);
              if (data.result) {
                $('#photo-' + data.fid).fadeOut('fast', function() {
                  $(this).remove();
                  
                  if (!$('#photolist li').size()) {
                    if (!$('#photolist-empty').size()) {
                      $('#photolist').before('<div id="photolist-empty">' + Drupal.settings.photolist.translate.no_image + '<\/div>');
                    }
                    $('#photolist-list').hide();
                    $('#photolist-empty').show();
                    $('.swfUploadSave').fadeOut('fast');
                  } else {
                    if (!$('#photolist-list').size()) {
                      $('#photolist').before('<div id="photolist-list">' + Drupal.settings.photolist.translate.list_image + '<\/div>');
                    }
                    $('#photolist-list').show();
                    $('#photolist-empty').hide();
                  }
                });
              } else {
                // error
              }
            },
            error: function() {}
          });
        }
        return false;
      });

      // Sort album
      if (Drupal.settings.photolist.allowSorting) {
        $('#photolist').sortable({
          placeholder: 'ui-state-highlight',
          items: 'li:not(#photolist-empty)',
          forcePlaceholderSize: true,
          opacity: 0.6,
          revert: true,
          start: function(event, ui) {
            $('a.photolist-thumbnail-link').unbind('click.fb');
          },
          update: function(event, ui) {
            _initFancybox();
            if (!$('.photolist-update').size()) {
              var $btnUpdate = '<div class="photolist-update" style="display:none;"><button>' + Drupal.settings.photolist.translate.save_order + '<\/button><\/div>';
              $('#photolist').after($btnUpdate).before($btnUpdate);
            }
            $('.photolist-update').fadeIn('fast');
          }
        }).disableSelection();
        
        $('.photolist-update button').live('click', function(event, callback) {
          var $deltas = new Array();
          var $items = $('#photolist li').toArray();
          if (typeof callback!='undefined') var $callback = callback;
          else $callback = null;
          for (var i=0; i<$items.length; i++) {
            var $fid = $($items[i]).attr('id').match(/\d+/);
            if ($fid!=null) $deltas.push($fid.join(''));
          };
          
          $.ajax({
            type: 'POST',
            url: Drupal.settings.photolist.sortUrl,
            data: {deltas: $deltas},
            success: function(data) {
              //console.log(data);
              if (data.result) {
                $('.photolist-update').fadeOut('fast');
                if ($callback!=null) $callback();
              } else alert(data.error);
            }
          });
        });
      }
      
      // Edit photo title
      $('#photolist .desc-img').live('click', function() {
        $(this).hide();
        var $fid = $(this).attr('id').match(/\d+/).join('');
        var $update_url = Drupal.settings.photolist.updateUrl + '/' + $fid;
        var $frmTitle = $('<input id="desc-'+$fid+'" value="'+$(this).attr('title')+'"\/>');
        $frmTitle.insertAfter($(this)).focus();
        if (Drupal.settings.photolist.allowSorting) {
          $('#photolist').enableSelection();
        }
        
        $($frmTitle).bind('blur keypress', function(event){
          var self = $(this);
          var prev = self.prev();
          if (event.type=='keypress' && event.keyCode!=13) return;
          var value = $(this).attr('value');
          $(prev).show();
          self.remove();
          if (Drupal.settings.photolist.allowSorting) {
            $('#photolist').disableSelection();
          }
          $(prev).attr('title', value);
          if (value!='') $(prev).html(value); else $(prev).html(Drupal.settings.photolist.translate.edit_desc);
          $.ajax({
            data: {title: value},
            url: $update_url,
            type: 'POST',
            success: function(data) {
              //console.log(data);
              if (!data.result) alert(data.error);
              else {
                var value = data.title; 
                $(prev).attr('title', value);
                if (value!='') $(prev).html(value); else $(prev).html(Drupal.settings.photolist.translate.edit_desc);
                $('#photo-' + data.fid + ' a').attr('title', value);
              }
            },
            complete: function() {
              
            }
          });
        });
      });
      
      // Finish
      $('.swfUploadSave button').live('click', function() {
        if ($('.photolist-update').size() && !$('.photolist-update:hidden').size()) {
          $('.photolist-update :button:first').trigger('click', [function() {
            window.location = Drupal.settings.photolist.nodeUrl;
          }]);
        }
        else window.location = Drupal.settings.photolist.nodeUrl;
      });
    }
  };
})(jQuery);